/**
 * Description:基于配置文件的表格
 * Copyright: 成都和为科技有限公司 2012
 * author:zhouxingxing
 * CreateDate: 2015-06-01
 * <DataGrid rowNum="10" rowList="[10,20,30]" multiselect="true">
    	<col title="" name=""  path=""  sort=""  width="" align=""  sortable="false"/>
    	<col .../>
   </DataGrid>

   DataGrid
	  属性：
	    - rownum : 一页显示多少行数据  默认：10
	    - rowlist: 可更改一页显示数据行数  默认: [10,20,30,50,100]
	    - multiselect: 支持选择  默认:false
	    - recordpos: 记录显示位置  [left center right] 默认: left
	    - pageable : 是否支持翻页. 默认：true
	    - caption : 表格标题
        - sort : 表格排序字段
        - sorttype: 表格排序方式, 默认desc
	    - grouping : 分组.  默认false
	    - groupfield : 按哪列分组，对应col的path属性
	    - grouptext : 分组行显示内容. 默认：<b>{0}</b>.  即：显示分组名字
	    - groupcollapse : 分组收缩. 默认为false
	    - grouporder : 分组排序. 默认['asc']
	    - groupsummary : 分组求和 [true]
	    - subgrid : true | false 默认 false 增加展开栏的按钮
	    - onexpandpanel 展开内容id
		- showquery : 显示高级查询, true | false 默认 false
		- excel true|false 默认true
		- params - 固定查询参数
	  事件：
	    - onselectrow ：选择行
	    - onselectall : 选择所有
	    - gridcomplete : 表格加载完成
	    - onexpandrow : 扩展行
	    - oncollapserow : 收缩行
	    - beforeshow : 显示数据前调用
	    - onpaging : 翻页回调事件
	col
	  属性：
	    - title : 列标题。 显示在表头
	    - name : 列名字
	    - path : 列路径, 用于绑定数据
	    - sort : 排序标识
	    - width : 宽度
	    - align : 文字显示位置
	    - hidden : 隐藏列。默认false
	    - sortable : 是否支持排序, 如果有sort标识,默认为true,否则默认为false;
	    - resizable : 是否支持拉伸, 默认true
	    - formatter : 格式化数据 [number || date]
	    - summarytype : 'min | max | sum' 求和类型
	    - summarytpl : '<b>Max: {0}</b>'  显示内容
        - edittype : 高级查询使用. 查询输入控件类型
        - editattr : 高级查询使用. 查询输入控件属性
        - queryprex : 高级查询使用. 数据库查询前缀
	  事件:
	    - cellattr ：列属性
	    - formatter : 格式化显示当前数据
	    - click : 点击
 */
function DataGrid() {}

DataGrid.inherit(Control);

/**
 * 初始化方法
 */
DataGrid.prototype.init = function () {
	DataGrid.base.init.call(this);
}

DataGrid.prototype.create = function() {
	this._html = document.createElement("div");
	var sRandomID = Math.uuid();
	var tableid = "#" + sRandomID + "_table";
	var pageid = "#" + sRandomID + "_page";
	this._tableid = tableid;
	this._pageid = pageid;
	$(this._html).append(
		"<table id=" + sRandomID + "_table></table>" +
		"<div id=" + sRandomID + "_page></div>"
	);
}

DataGrid.prototype.initLoad = function() {
	if(!$().jqGrid) {
		this.loadCSSFile("/public.common/webapi/common/jqgrid/jquery-ui.theme.css");
		this.loadCSSFile("/public.common/webapi/common/jqgrid/ui.jqgrid.css");
		this.loadCSSFile("/public.common/webapi/common/jqgrid/ui.jqgrid-bootstarp.css");
		this.loadScriptFile("/public.common/webapi/common/jqgrid/grid.locale-cn.js");
		this.loadScriptFile("/public.common/webapi/common/jqgrid/jquery.jqGrid.src.js");
	}
	var config = this.getConfig();
	this._config = config;
	if (config.pageable)
		config.pager = this._pageid;
	this._jqgrid = $(this._tableid, this.getHTML()).jqGrid(config)
		.navGrid(this._pageid, {view:false,edit:false,del:false,
		add:false,search:false,refresh:false,position:"right"});
	
	//增加导出excel
	var othis = this;
//	if (this.getAttribute().excel != "false") {
	if (this.getAttribute().excel == "true") {//暂时把所有导出excl屏蔽掉，除非页面上面写了excel=ture
		$(this._tableid).navButtonAdd(this._pageid,{
		   caption:"Excel&nbsp",
		   buttonicon:"ui-icon-document",
		   position:"last",
		   onClickButton: function(){
				othis.exportExcel();
		   }
		});
	}
	//增加高级查询
	if (this.getAttribute().showquery == "true") {
		//高级查询
		$(this._tableid).navButtonAdd(this._pageid,{
		   caption:"高级查询&nbsp",
		   buttonicon:"ui-icon-search",
		   position:"first",
		   onClickButton: function(){
		   	   othis.showAdvanceQuery();
		   }
		});
	}
	if (this.getAttribute().params) {
        var sParam = this.getAttribute().params.replaceAll("'","\"");
        var oParam = JSON.parse(sParam);
        this._fixParam = oParam;
    }
}

DataGrid.prototype.getConfig = function() {
	var othis = this;

	var config = new Object();
	config.datatype = "json";
	config.viewrecords = true;
	config.emptyrecords = "无结果记录.";
	var width = this.getAttribute().width;

	if (width && width != "100%") {
		$(this.getHTML()).css("width", width);
	}
	
	width = $(this.getHTML()).width();
	config.width = width ? width : "auto";
	config.height = this.getAttribute().height ? this.getAttribute().height : "auto";
	config.rowNum = this.getAttribute().rownum ? parseInt(this.getAttribute().rownum) : 10;
	config.rowList = this.getAttribute().rowlist ? eval(this.getAttribute().rowlist) : [10,20,50,100,200];
	config.multiselect = this.getAttribute().multiselect ? eval(this.getAttribute().multiselect) : false;
	config.recordpos = this.getAttribute().recordpos ? this.getAttribute().recordpos : "left";
	config.pageable = this.getAttribute().pageable ? eval(this.getAttribute().pageable) : true;
	config.caption = this.getAttribute().caption ? this.getAttribute().caption : "";
	config.subGrid = this.getAttribute().subgrid ? eval(this.getAttribute().subgrid) : false;
    config.sort = this.getAttribute().sort ? this.getAttribute().sort : "";
    if (config.sort != "") {
        config.sort += ":";
        config.sort += this.getAttribute().sorttype ? this.getAttribute().sorttype : "desc";
    }
	//分组
	config.grouping = this.getAttribute().grouping ? eval(this.getAttribute().grouping) : false;
	if (config.grouping) {
		config.groupingView = new Object();
		config.groupingView.groupField = this.getAttribute().groupfield ? eval(this.getAttribute().groupfield) : [];
		config.groupingView.groupSummary = this.getAttribute().groupsummary ? eval(this.getAttribute().groupsummary) : [false];
		config.groupingView.groupColumnShow = this.getAttribute().groupcolumnshow ? eval(this.getAttribute().groupcolumnshow) : [false];
		config.groupingView.groupText = this.getAttribute().grouptext ? eval(this.getAttribute().grouptext) : ['<b>{0} - 数量:{1} </b>'];
//		config.groupingView.groupCollapse = this.getAttribute().groupCollapse ? eval(this.getAttribute().groupCollapse) : [false];
	}
	//加载列
	config.colNames = new Array();
	config.colModel = new Array();
	var cols = $(this.getElement()).children();

	for (var i = 0 ; i < cols.length; i++) {
		var col = cols[i];
        var oAttr = new Object();
        var model = new Object();
        for (var j = 0 ; j < col.attributes.length ; j++) {
            var atrr = col.attributes[j];
            oAttr[atrr.name] = atrr.value;
            model[atrr.name] = atrr.value;
        }
		var title = oAttr.title ? oAttr.title : "";
		config.colNames.push(title);
		model.name = oAttr.path ? oAttr.path : "";
		model.title = title;
		model.width = oAttr.width ? oAttr.width : "";
		model.align = oAttr.align ? oAttr.align : "left";
		model.index = oAttr.sort ? oAttr.sort : "";
		model.hidden = oAttr.hidden ? eval(oAttr.hidden) : false;
		//根据sort标识自适应
		if (oAttr.sortable) {
			model.sortable = eval(oAttr.sortable);
		} else {
			if (oAttr.sort) {
				model.sortable = true;
			} else {
				model.sortable = false;
			}
		}
		model.resizable = oAttr.resizable ? eval(oAttr.resizable) : true;
//		model.datefmt = oAttr.datefmt ? oAttr.datefmt : "Y-m-d";
		if(oAttr.click) model.click = oAttr.click;

		if(oAttr.edittype) model.edittype = oAttr.edittype; //编辑类型
		if(oAttr.editattr) model.editattr = oAttr.editattr; //编辑属性
		if(oAttr.queryprex) model.queryprex = oAttr.queryprex; //查询前缀

		model.text = oAttr.text ? oAttr.text : "";
		if (oAttr.formatter) {
			//事件
			model.format = oAttr.formatter;
			if (this.isScriptValue(oAttr.formatter)) {
				model.formatter = function(value, options, rData) {
					var formatter = othis.getColDef(options.colModel.name).format;
					return othis.triggerEvent(formatter, value, options, rData);
				}
			} else {
				switch (oAttr.formatter) {
					case "button":
						model.formatter = othis.handlerButton;
						break;
					default :
						model.formatter = oAttr.formatter;
				}
			}
		}
		if (oAttr.summarytype) model.summaryType = oAttr.summarytype;
		if (oAttr.summarytpl) model.summaryTpl = oAttr.summarytpl;
		config.colModel.push(model);
	}
	/** 绑定事件 */
	config.gridComplete = function() {
		othis.triggerAttributeEvent("gridcomplete");
	}
	//列点击
	config.onCellSelect = function(rowid, iCol, cellcontent, e) {
		if (config.subGrid) iCol--;
		if (config.multiselect) iCol--;
		var colDef = config.colModel[iCol];
		if (colDef && colDef.click) {
			othis.triggerEvent(colDef.click, rowid, iCol, cellcontent, e)
			othis.setSelection(rowid);
		}
	}
	if (config.subGrid) {
		//展开行
		config.subGridRowExpanded = function(subgrid_id, row_id) {
            //收缩当前行
            if (othis._expandid && row_id != othis._expandid) {
                othis.onRowExpand(othis._expandid);
            }
			var sExpandPanelId = othis.getAttribute().onexpandpanel;
			var oExpandPanel = othis.getComponent().getElementById(sExpandPanelId);
			oExpandPanel.show();
			$("#"+subgrid_id).css("padding","5px");
			$("#"+subgrid_id).append(oExpandPanel.getHTML());

			//回调事件
            try {
                othis.triggerAttributeEvent("onexpandrow",
                    oExpandPanel, subgrid_id, row_id);
            } catch (e) {}
            othis._expandid = row_id;
		}
		//收缩行
		config.subGridRowColapsed = function(subgrid_id, row_id) {
            if (othis._expandid == row_id) {
                othis._expandid = null;
            }
			//回调事件
			othis.triggerAttributeEvent("oncollapserow", subgrid_id, row_id);
		}
	}
	//行选择
	config.onSelectRow = function(rowid, status) {
		othis.triggerAttributeEvent("onselectrow", rowid, status);
	}
	//选择所有
	config.onSelectAll = function(aRowids, status) {
		othis.triggerAttributeEvent("onselectall", aRowids, status);
	}
	//排序
	config.onSortCol = function(index, iCol, sSortorder) {
        othis._config.sort = "";
		if (othis._config.grouping) {
			var gfs = othis._config.groupingView.groupField;
            var sort = "";
			for (var i = 0 ; i < gfs.length ; i++) {
				var col = othis.getColDef(gfs[i]);
                sort += col.index + ":desc ";
			}
            othis._config.sort = sort.trim();
		}
        if (othis._config.sort != "") {
            othis._config.sort += " ";
        }
        othis._config.sort += index + ":" + sSortorder;
		othis.queryAndDisplay();
	}
	//翻页
	var pageid = this._pageid;
	var onPaging = this.getAttribute().onpaging;
	config.onPaging = function(value){
		var iPageNum;
		switch (value) {
			case "first" :
				iPageNum = 1;
				break;
			case "prev" :
				iPageNum = othis._data.page - 1;
				break;
			case "next" :
				iPageNum = othis._data.page + 1;
				break;
			case "last" :
				iPageNum = othis._data.total;
				break;
			case "user":
				var iPageNum = $(pageid + " input", othis.getHTML()).val();
				//验证页码是否是正整数
				var type="^[0-9]*[1-9][0-9]*$";
				var re = new RegExp(type);
				if(!iPageNum.match(re))
				{
					WinUtil.showTip($(pageid + " input", othis.getHTML()), {
						title : "请输入正整数!",
						placement:"left"
					});
					return;
				} 
				iPageNum = parseInt(iPageNum);
				//如果页码大于最大页码 
				if(iPageNum > othis._data.total)
					iPageNum = othis._data.total;
					
				break;
			case "records" :
			 	var rowNum = $(pageid + " select option:selected", othis.getHTML()).val();
			 	othis._config.rowNum = parseInt(rowNum);
			 	othis.setGridParam({rowNum:parseInt(rowNum)});
			 	iPageNum = 1;
			 	break;
		}
		
		othis.goPage(iPageNum, true, function(oTable, oData) {
			othis.triggerAttributeEvent("onpaging", oData);
		});
	}
	return config;
}

/**
 * 获得列定义
 * @param {} sColName
 */
DataGrid.prototype.getColDef = function(sColName) {
	for (var i = 0 ; i < this._config.colModel.length ; i++) {
		var oColDef = this._config.colModel[i];
		if (oColDef.name == sColName || oColDef.index == sColName) {
			return oColDef;
		}
	}
}

/**
 * 通过列号获得列定义
 */
DataGrid.prototype.getColDefByNum = function(sColNum) {
	return this._config.colModel[sColNum];
}


/**
 * 查询并显示结果
 * @param {} oParam 若为空，则执行上次查询
 * @param {} bAsync 是否异步显示表格, 默认为true
 * @param {} oCallBack 当表格加载完，回调方法
 */
DataGrid.prototype.queryAndDisplay = function(oParam, bAsync, oCallBack) {
	if (oParam) {
		this._oQueryParam = this.buildParam(oParam);
	}
	this.goPage(1, bAsync, oCallBack);
}

/**
 * 建立条件
 * @param {} oParam
 * @return {}
 */
DataGrid.prototype.buildParam = function(oParam) {
	if (this._fixParam) {
		for (var sCont in this._fixParam) {
			oParam[sCont] = this._fixParam[sCont]
		}
	}
	return oParam;
}

/**
 * 跳到多少页并显示
 * @param {} iPageNum
 */
DataGrid.prototype.goPage = function(iPageNum, bAsync, oCallBack) {
    if (typeof (bAsync) == "undefined") bAsync = true;
    if (bAsync) {
        var othis = this;
        this._jqgrid.beginReq();
        setTimeout(function(){
            othis.showPage(iPageNum, oCallBack);
            othis._jqgrid.endReq();
        },100);
    } else {
        this.showPage(iPageNum);
    }
}

/**
 * 显示表格数据
 * @param {} iPageNum 页码
 */
DataGrid.prototype.showPage = function(iPageNum, oCallBack) {
	$("input:checked",this._html).removeAttr("checked");
    this.onCurrentRowCollapse();
	//-----------------------------
	var rowStart = this._config.rowNum * (iPageNum - 1);
    //封装请求参数
    var oRequest = new Object();
    oRequest.rownum = parseInt(this._config.rowNum);
    oRequest.start = rowStart;
    oRequest.rowcount = true;
    if (this._oQueryParam) oRequest.params = this._oQueryParam;
    if (this._config.sort != "") oRequest.sort = this._config.sort;
	var oResult = this.getDataSource().queryData(oRequest);
	this._data = new Object();
	this._data.page = iPageNum;
	if (oResult.count == 0) {
		iPageNum = 0;
	}
    this._count = oResult.count;
	this._data.records = this._count;
	var total = parseInt(this._count/this._config.rowNum)
	if (this._count%this._config.rowNum != 0) {
		total++;
	}
	this._data.total = total;
	this._data.rows = oResult.records;
	this.clear(true);
	if (this._config.grouping) {
		this._jqgrid.initGroup();
	}
	this.triggerAttributeEvent("beforeshow", this._data);
	this.addJSONData(this._data);
	this.setWidth();
//	this.setGridWidth($(this.getHTML()).width());
	//----------------------------
	if (oCallBack) {
		oCallBack(this, this._data);
	}
}

/**
 * 延迟设置表格填充宽度
 */
DataGrid.prototype.setWidth = function(){
    if($(this.getHTML()).width() == 0){
        var that = this;
        setTimeout(function() {
            that.setWidth();
        },100);
    }else{
        this.setGridWidth($(this.getHTML()).width());
    }
}


DataGrid.prototype.getCurrentPage = function() {
	return this._data.page;
}

/**
 * 获得总记录条数
 * @return {}
 */
DataGrid.prototype.getTotalRecord = function() {
	return this._count;
}

DataGrid.prototype.getTotalPage = function() {
	return this._data.total;
}

/**
 * 重加载当前页数据
 */
DataGrid.prototype.reshow = function(bAsync, oCallBack) {
	this.goPage(this._data.page, bAsync, oCallBack);
}

/**
 * 特殊处理行按钮
 * @param {} value
 * @param {} options
 * @param {} rData
 * @return {}
 */
DataGrid.prototype.handlerButton = function(value, options, rData) {
	var text = "";
	if (value) {
		text = value;
	} else {
		text = options.colModel.text;
	}
	return "<span class='data-grid-col-btn' style='color:#06c;cursor:pointer;'>"
		+ text + "</span>";
}

/**
 * 返回所有行id数组
 * @return {}
 */
DataGrid.prototype.getDataIDs = function(){
	return this._jqgrid.getDataIDs();
}

/**
 * 插入一新行，rowid 为新行的ID，data（数组）为新行数据，
 * position为新行插入的位置（first为表头，last为表尾，srcrowid指定偏移位置）。
 * Data数组的格式为：{name1:value1,name2: value2…} ，name为colModel指定的名称。
 * @param {} rowId
 * @param {} oData
 * @param {} position
 * @param {} srcrowid
 */
DataGrid.prototype.addRowData = function(rowId, oData, position, srcrowid) {
	this._jqgrid.addRowData(rowId, oData, position, srcrowid);
}

/**
 * 删除id = rowid的行。但不会删除服务器上的数据。
 * @param {} rowId
 */
DataGrid.prototype.delRowData = function(rowId) {
	this._jqgrid.delRowData(rowId);
}

/**
 * 设置行数据
 * @param {} rowId 行id
 * @param {} content 内容
 */
DataGrid.prototype.setRowData = function(rowId, oData) {
	this._jqgrid.setRowData(rowId, oData);
}

/**
 * 获得行数据, 不传行id,则返回所有行数据数组
 * @param {} rowId 行id
 * @return {}
 */
DataGrid.prototype.getRowData = function(rowId) {
	return this._jqgrid.getRowData(rowId);
}

/**
 * 返回表格数据
 * @param {} rowId
 */
DataGrid.prototype.getData = function(rowId) {
	if (!rowId) {
		return this._data.rows;
	} else {
		for (var i = 0 ; i < this._data.rows.length; i++) {
			var oRecord = this._data.rows[i];
			if (rowId == oRecord.id) {
				return oRecord;
			}
		}
	}
}

/**
 * 设置指定列标题文字、属性和类：
 * @param {} sColname 列名，可以是从0开始的列索引；
 * @param {} sTitle 标题文字，为空则不修改；
 * @param {} sClass 若为字符串，则为类名，若为数组，则直接写入CSS；
 * @param {} oProperties 标题文字的属性。
 */
DataGrid.prototype.setColTitle = function(sColname, sTitle, sClass, oProperties) {
	this._jqgrid.setLabel(sColname, sTitle, sClass, oProperties);
}

/**
 * 设置新的表头文字。若表头为隐藏，将显示。
 * @param {} sName
 */
DataGrid.prototype.setCaption = function(sName) {
	this._jqgrid.setCaption(sName);
}

/**
 * 修改单元格的值、类或样式
 * @param {} rowId 行id
 * @param {} sColname 列名（可以是从0开始的列的索引值）；
 * @param {} sData 值
 * @param {} sClass 为字符串，将使用addClass为列加入一个类，若为数组，将直接加入CSS中
 * @param {} oProperties 设置单元格属性。
 * @param {} bForceup
 */
DataGrid.prototype.setCell = function(rowId, sColname, sData, sClass, oProperties, bForceup) {
	this._jqgrid.setCell(rowId, sColname, sData, sClass, oProperties, bForceup);
}

/**
 * 返回指定rowid，iCol的单元格内容，
 * iCol既可以是当前列在colModel中的位置索引也可以是name值。
 * @param {} rowId
 * @param {} iCol
 * @return {}
 */
DataGrid.prototype.getCell = function(rowId, iCol) {
	return this._jqgrid.getCell(rowId, iCol);
}

/**
 * 选择或反选id = rowid指定的行。若onselectrow设置为true (缺省)
 * 则触发onSelectRow事件，否则不触发。
 * @param {} rowId
 * @param {} onselectrow
 */
DataGrid.prototype.setSelection = function(rowId, onselectrow) {
	this._jqgrid.setSelection(rowId, onselectrow);
}

/**
 * 全选或反选行
 */
DataGrid.prototype.resetSelection = function() {
	this._jqgrid.resetSelection();
}

/**
 * 获得多行选中. 复选框
 * @return {}
 */
DataGrid.prototype.getSelection = function() {
	return this._jqgrid.getGridParam("selarrrow");
}

/**
 * 获得单行选中
 * @return {}
 */
DataGrid.prototype.getSelect = function() {
	return this._jqgrid.getGridParam("selrow");
}

/**
 * 动态设置表格的高度。参数说明如下
   height ：表格宽度（单位px）
 */
DataGrid.prototype.setGridHeight = function(height) {
	this._jqgrid.setGridHeight(height);
}

/**
 * 动态设置表格的宽度。参数说明如下
   width ：表格宽度（单位px）
 */
DataGrid.prototype.setGridWidth = function(width) {
	this._jqgrid.setGridWidth(width);
}

DataGrid.prototype.resetWidth = function() {
	this.setGridWidth($(this.getHTML()).width());
}

/**
 * 根据colname或colnames数组给定的列名隐藏相应的列，
 * 列名必须是colModel中定义的名称。表格的宽度不会改变。
 * @param {} sColname
 */
DataGrid.prototype.hideCol = function(sColname) {
	this._jqgrid.hideCol(sColname);
}

/**
 * 显示列
 * @param {} sColname
 */
DataGrid.prototype.showCol = function(sColname) {
	this._jqgrid.showCol(sColname);
}

/**
 * 清除网格中当前装入的数据，如果clearfooter 参数为true，
 * 则清除网格最后一行数据。
 * @param {} bClearfooter
 */
DataGrid.prototype.clear = function(bClearfooter) {
	this._jqgrid.clearGridData(bClearfooter);
}

/**
 * 用传递的data（数组）填充网格。
 * @param {} data
 */
DataGrid.prototype.addJSONData = function(data) {
	this._jqgrid[0].addJSONData(data);
}

/**
 * 设置表格参数
 * @param {} oParam
 */
DataGrid.prototype.setGridParam = function(oParam) {
	this._jqgrid.setGridParam(oParam);
}

/**
 * 收缩当前展开行
 */
DataGrid.prototype.onCurrentRowCollapse = function() {
    if (this._expandid) {
        this.onRowExpand(this._expandid);
    }
}

/**
 * 展开或收缩行
 * @param {} rowId 行id
 */
DataGrid.prototype.onRowExpand = function(rowId) {
    var oRowHTML = $("#"+rowId, this.getHTML());
    $(".ui-sgcollapsed", oRowHTML).trigger("click");
}

/**
 * 展开下一条
 * @param {} rowId
 */
DataGrid.prototype.onRowExpandNext = function(currentRowId) {
	var oNextHtml = $("#"+currentRowId, this.getHTML()).next();
	$(".ui-sgcollapsed", oNextHtml).trigger("click");
}

/**
 * 设置排序
 * @param sort
 */
DataGrid.prototype.setSort = function(sort) {
    this._config.sort = sort;
}

/**
 * 导出excel
 * @param {} oParam
 */
DataGrid.prototype.exportExcel = function(oParam) {
	if (this._oQueryParam && typeof(oParam) == "undefined") {
		oParam = this._oQueryParam;
	}
    if (typeof(oParam) == "undefined") {
        oParam = {};
    }
	this.getDataSource().exportExcel(oParam,this.getTotalRecord());
}

DataGrid.prototype.setValue = function(oData) {
	this.clear();
    for (var i = 0 ; i < oData.length ; i++) {
        this.addRowData(oData[i].id, oData[i]);
    }
//    this.setGridWidth($(this.getHTML()).width());
    this.setWidth();
    this._data = new Object();
    this._data.total = oData.length;
    this._data.rows = oData;
}
/**
 * 返回获取到的值
 * @returns {*}
 */
DataGrid.prototype.getValue = function() {
	return this.getRowData();
}

/**
 * 设置固定查询参数
 * @param {} oParam
 */
DataGrid.prototype.setParam = function(oParam) {
	this._fixParam = oParam;
}

/**
 * 获得固定查询参数
 * @return {}
 */
DataGrid.prototype.getParam = function() {
	return this._fixParam;
}



DataGrid.prototype.showAdvanceQuery = function() {
	if (!this._oAQC) {
		this.addColumnsProp(); //增加列定义属性
		this.buildAdvanceParams();
	}
	this._oAQC.show();
    WinUtil.openDialog(this._oAQC.getHTML(), {title:"高级查询"});
}

/**
 * 为列增加属性，(类型,code值,数据库值)。用于高级查询
 */
DataGrid.prototype.addColumnsProp = function() {
	var aColDef = this.getColumns();
	var aColModel = this._config.colModel;
	for (var i = 0 ; i < aColModel.length ; i++) {
		var oColModel = aColModel[i];
		for (var j = 0 ; j < aColDef.length ; j++) {
			var oColDef = aColDef[j]["@attributes"];
			if (oColModel.name == oColDef.nm) {
				oColModel.type = oColDef.type;
				if(oColDef.cc) oColModel.code = oColDef.cc;
				oColModel.metadata = oColDef.md;
			}
		}
	}
}

/**
 * 获得列定义
 * @return {}
 */
DataGrid.prototype.getColumns = function() {

	var sDS = this.getAttribute().dataSource;
	var oDS = this.getComponent().getElementById(sDS);
	var soap = new HWSOAP("/hwsvr2/qe","query",
		"<c>" + oDS.getQueryConfig() + "<\/c>",
		"<qw type='column_format'\/>");
	soap.send();
	var sr = soap.getResult();
	if (sr) {
		return sr.resultdata.column_format.col;
	}
	return new Array();
}

DataGrid.prototype.addInput = function(oParam, oQueryContainer) {
	var type = oParam.ty;
	var oInput;
	switch (type){
		case "int" :
			if (oParam.cc) {
				var op = new Object();
				op.refResource = "code." + oParam.cc;
				op.parentAllow = "true";
				if (oParam.pk) op.refRootKey = oParam.pk;
				if (oParam.pl) op.refRootLevel = oParam.pl;
				var oDS = oQueryContainer.addItem("CodeService", op);
				var oControlName = "SuggestInput";
				if (oParam.ety)  oControlName = oParam.ety;
				oInput = Control.newInstance(oControlName,
					{check:"true", dataSource:oDS.getAttribute().id});
			} else {
				oInput = Control.newInstance("TextInput", {});
			}
			break;
		case "date" :
			oInput = Control.newInstance("DateField", {});
			break;
		case "datetime" :
			oInput = Control.newInstance("DateField", {});
			break;
		default :
			oInput = Control.newInstance("TextInput", {});
	}
	oInput.getAttribute().queryName = oParam.nm;
	oInput.getAttribute()["class"] = "query_input";
	oInput.init();
	oQueryContainer.addElement(oInput);
	oInput.initLoad();
	return oInput;
}

/**
 * 建立高级查询
 */
DataGrid.prototype.buildAdvanceParams = function() {
	var oAQC = this.getComponent().addItem("Group", {"class":"queryadvcnt"});
	oAQC.hide();
	this._oAQC = oAQC;
	var oSQLDisplay = oAQC.addItem("Label", {id:"aqc_detail", text:""});
	var oGroup = this.addQueryGroup(oAQC);
	$(".query_button_delgroup", oAQC.getHTML()).detach();

	//按钮
	var oResetBtn = oAQC.addItem("Button", {
		text:"重置", "class":"query_button", "float":"left", clear:"both",
		iconClass:"ui-icon-arrowreturnthick-1-w"
	});
	var oQueryBtn = oAQC.addItem("Button", {
		text:"查询", "class":"query_button", "float":"right",
		iconClass:"ui-icon-search"
	});
	var oShowBtn = oAQC.addItem("Button", {
		text:"查看语句", "class":"query_button", "float":"right",width:"80px",
		iconClass:"ui-icon-comment"
	});
	var othis = this;

	$(oResetBtn.getHTML()).click(function(){
		oAQC.delItem(oGroup);
		oGroup = othis.addQueryGroup(oAQC);
		$(".query_button_delgroup", oAQC.getHTML()).detach();
		$(oSQLDisplay.getHTML()).after(oGroup.getHTML());//放在最前面
	});
	$(oShowBtn.getHTML()).click(function(){
		var sSQL = othis.buildGroupSQL(oGroup);
		oSQLDisplay.setValue(sSQL);
	});
	$(oQueryBtn.getHTML()).click(function(){
		var sSQL = othis.buildGroupSQL(oGroup);
		sSQL = sSQL.replaceAll("<", "&lt;");
		sSQL = sSQL.replaceAll(">", "&gt;");
		if (sSQL != "")
			othis.queryAndDisplay({"querytext":sSQL});
		else
			othis.queryAndDisplay({});
	});
}

/**
 * 增加查询分组
 * @param {} oContainer
 */
DataGrid.prototype.addQueryGroup = function(oContainer) {
	var oHandler = oContainer.addItem("Group", {"class":"query_group", group:true});
	var oHandSelect = oHandler.addItem("ComboBox",
		{width:"80px", id:"grpoperator", "class":"query_handselect", desable:"false"});
	var oAddGroupBtn = oHandler.addItem("Button",
		{text:"+ ()", "class":"query_button_addgroup"});
	var oAddRecordBtn = oHandler.addItem("Button",
		{text:"+", "class":"query_button_addrecord"});
	var oDelGroupBtn = oHandler.addItem("Button",
		{text:"-", "class":"query_button_delgroup"});

	this.buildGroupOperator(oHandSelect);
	var othis = this;
	$(oAddGroupBtn.getHTML()).click(function(){
		othis.addQueryGroup(oHandler);
	});
	$(oAddRecordBtn.getHTML()).click(function(){
		othis.addQueryRecord(oHandler);
	});
	$(oDelGroupBtn.getHTML()).click(function(){
		oContainer.delItem(oHandler);
	});
	return oHandler;
}

DataGrid.prototype.addQueryRecord = function(oContainer) {
	var oRecord = oContainer.addItem("Group", {"class":"query_record", record:true});
	var oColumn = oRecord.addItem("ComboBox",
		{"id":"column","class":"query_column"});
	var oOperator = oRecord.addItem("ComboBox",
		{"id":"operator","class":"query_operator",desable:"false"});
	var oInput = oRecord.addItem("TextInput",
		{"id":"input","class":"query_input"});
	var oDel = oRecord.addItem("Button", {text:"-","class":"button_delete_record"});
	this.buildRecordOperator(oOperator);
	this.buildRecordColumns(oColumn);
	var othis = this;
	$(oColumn.getHTML()).change(function(){
		var value = oColumn.getValue();
		var oColRef = othis.getColDef(value);
		//变更输入控件
		var oParam = new Object();
		oParam.ty = oColRef.type;
		oParam.cc = oColRef.code;
		oParam.nm = oColRef.name;
		oRecord.delItem(oInput);
		oInput = othis.addInput(oParam, oRecord);
		oRecord.getElements()["input"] = oInput;//设置id
		$(oDel.getHTML()).before(oInput.getHTML());
		//改变操作符的值
		var oOperator = oRecord.getElementById("operator");
		othis.buildRecordOperator(oOperator, oColRef.type, oColRef.code);
	});
	$(oDel.getHTML()).click(function(){
		oContainer.delItem(oRecord);
	});
}

DataGrid.prototype.buildGroupOperator = function(oSelect) {
	oSelect.addItem({name:"所有", value:"AND"});
	oSelect.addItem({name:"任一", value:"OR"});
}

/**
 * 建立记录操作下拉列表
 * @param {} sType
 */
DataGrid.prototype.buildRecordOperator = function(oSelect, sType, sCode) {
	oSelect.clearItem();
	oSelect.addItem({name:"等于", value:"= {0}"});
	oSelect.addItem({name:"不等于", value:"!= {0}"});
	if ((sType == "int" && !sCode) || sType == "numeric" ||
		sType == "date" || sType == "datetime") {
		oSelect.addItem({name:"小于", value:"&lt; {0}"});
		oSelect.addItem({name:"小于等于", value:"&lt;= {0}"});
		oSelect.addItem({name:"大于", value:"&gt; {0}"});
		oSelect.addItem({name:"大于等于", value:"&gt;= {0}"});
	}
	if (sType == "string") {
		oSelect.addItem({name:"开始于", value:"LIKE \"{0}%\""});
		oSelect.addItem({name:"不开始于", value:"NOT LIKE \"{0}%\""});
		oSelect.addItem({name:"结束于", value:"LIKE \"%{0}\""});
		oSelect.addItem({name:"不结束于", value:"NOT LIKE \"%{0}\""});
		oSelect.addItem({name:"包含", value:"LIKE \"%{0}%\""});
		oSelect.addItem({name:"不包含", value:"NOT LIKE \"%{0}%\""});
	}
	oSelect.addItem({name:"空值", value:"IS NULL"});
	oSelect.addItem({name:"非空值", value:"IS NOT NULL"});
//	oSelect.addItem({name:"具有", value:"IN ({0})"});
//	oSelect.addItem({name:"不具有", value:"NOT IN ({0})"});
}

/**
 * 建立记录查询列
 * @param {} oSelect
 */
DataGrid.prototype.buildRecordColumns = function(oSelect) {
	//加载列
	for (var i = 0 ; i < this._config.colModel.length ; i++) {
		var oColModel = this._config.colModel[i];
		if (oColModel.name != "" && !oColModel.hidden) {
			var sName = oColModel.title;
			var sValue = oColModel.index;
			oSelect.addItem({name:sName, value:sValue});
		}
	}
}

/**
 * 建立查询SQL语句
 * @param {} oGroup
 */
DataGrid.prototype.buildGroupSQL = function(oGroup) {
	var op = oGroup.getElementById("grpoperator").getValue();
	var sSQL = "";
	var found = false;
	for (var i in oGroup.getElements()) {
		var oEle = oGroup.getElements()[i];
		if (oEle.getAttribute().group) {
			var sGrpSQL = this.buildGroupSQL(oEle);
			if (sGrpSQL != "") {
				sSQL += sGrpSQL + " " + op + " ";
				found = true;
			}
		} else if (oEle.getAttribute().record) {
			var sRecSQL = this.buildRecordSQL(oEle);
			if (sRecSQL != "") {
				sSQL += sRecSQL + " " + op + " ";
				found = true;
			}
		}
	}
	//去掉最后一个连接符
	if (found) {
		var oplength = op.length + 2;
		sSQL = sSQL.substring(0, sSQL.length - oplength);
		sSQL = "(" + sSQL + ")";
		return sSQL;
	} else {
		return "";
	}
}

/**
 * 建立查询记录语句
 */
DataGrid.prototype.buildRecordSQL = function(oRecord) {
	var col = oRecord.getElementById("column").getValue();
	if (col == "") return "";
	var op = oRecord.getElementById("operator").getValue();
	var oInput = oRecord.getElementById("input")
	var value = oInput.getValue();
	if (value == "" && op.indexOf("NULL") == -1) return "";
	var sType = oInput.getType();
	var oColDef = this.getColDef(col);
	if (sType == "TextInput") {
		if (oColDef.type == "string"
			&& op.indexOf("LIKE") == -1) {
			value = "'" + value + "'";
		}
		value = op.replace("{0}", value);
		if (op.indexOf("LIKE") != -1) {
			value = value.replaceAll("\"", "'");
		}
	} else if (sType == "DateField") {
		value = "to_date('" + value + "', 'yyyy-mm-dd')";
		value = op.replace("{0}", value);
	} else if (sType == "SuggestInput") {
		var oResult = oInput.getResult();
		if (op.indexOf("IN") != -1 ||
			op.indexOf("NULL") != -1) {
			value = op.replace("{0}", value);
		} else {
			var value = "";
			for (var i = 0 ; i < oResult.length ; i++) {
				if (op == "= {0}") {
					value += oColDef.metadata + " BETWEEN "+oResult[i].d+" AND "+oResult[i].m;
				} else if (op == "!= {0}") {
					value += oColDef.metadata + " NOT BETWEEN "+oResult[i].d+" AND "+oResult[i].m;
				}
				value += " OR "
			}
			if (value != "") {
				value = value.substring(0, value.length - 3);
				value = "(" + value + ")";
				return value;
			} else {
				return "";
			}
		}
	}
	return oColDef.metadata + " " + value;
}


///**
// * 重写覆盖方法，解决分页不显示问题
// * @return {}
// */
//DataGrid.prototype.clone = function() {
//	var sType = this.getType();
//	var oAT = this.getAttribute();
//	var oControl = eval("new "+ sType +"()");
//	oControl.setResource(this.getResource());
//	oControl.setPath(this.getPath()+"/hw:" + sType);
//	if (oAT.name) {
//		oControl.setName(oAT.name);
//	}
//	oControl.setParent(this.getParent());
//	oControl.setRoot(this.getRoot());
//	oControl.setType(sType);
//	oControl.setComponent(this.getComponent());
//	oControl.init();
//	$("body").append(oControl.getHTML());
//	oControl.initLoad();
//	return oControl;
//}
